package com.deer.wms.intercept.common.data;

import com.deer.wms.intercept.dao.User2Mapper;
import com.deer.wms.intercept.security.JwtUtil;
import com.deer.wms.project.root.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.text.MessageFormat;

/**
 * Created by guo on 2017/9/29.
 */
@Service(value = "commonDataService")
public class CommonDataServiceManager implements CommonDataService {

    public static String ACCESS_TOKEN = "AccessToken:{0}";

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private User2Mapper user2Mapper;

    @Override
    public void putCurrentUserDataToRedis(CurrentUser currentUser) {
        if (null == currentUser || StringUtils.isEmpty(currentUser.getToken())) {
            return;
        }

//        String token = currentUser.getToken();
        String key = MessageFormat.format(ACCESS_TOKEN, currentUser.getAccount());
        redisUtil.set(key, currentUser);

        redisUtil.expire(key, 60L * 60 * 8);
        //  redisUtil.expire(key, 10L);
    }

    @Override
    public void removeCurrentUserDataFromRedis(String token) {
        String key = MessageFormat.format(ACCESS_TOKEN, token);
        redisUtil.delKey(key);
    }

    @Override
    public CurrentUser getCurrentUserDataFromRedis(String token) {
        String username = jwtUtil.getUsername(token);
        String key = MessageFormat.format(ACCESS_TOKEN, username);
        CurrentUser currentUser =  (CurrentUser)redisUtil.get(key);
//        if(currentUser==null){
//            UserInfo2 userInfo2 =user2Mapper.findByToken(token);
//            if(userInfo2!=null){
//                currentUser = new CurrentUser();
//                currentUser.setUserId(userInfo2.getUserId());
//                currentUser.setUserName(userInfo2.getUserName());
//            }
//        }

        return currentUser;
    }
}
